<template>
  <div class="analysis-container">
    <Nav></Nav>
    <div class="navbottom">
        <img src="../assets/Solid mood overjoyed.svg" alt="">
        <img src="../assets/Solid mood happy.svg" alt="">
        <img src="../assets/Solid mood neutral.svg" alt="">
        <img src="../assets/Solid mood sad.svg" alt="">  
        <img src="../assets/Solid mood depressed.svg" alt="">
        <img src="../assets/kule.svg" alt="">
    
      </div>

    <div class="main-content">
      <div class="chart-container">
        <!-- 心情趋势图 -->
        <div ref="moodTrendChart" class="chart" >
          <div v-if="loading" class="loading-tip">加载中...</div>
        </div>

          <!-- 月趋势图 -->
        <div class="chart-wrapper">
          <h3 class="chart-title">本月心情变化</h3>
          <div ref="moodMonthlyChart" class="chart monthly">
            <div v-if="loading" class="loading-tip">加载中...</div>
          </div>
        </div>


        <!-- 心情分布图 -->
        <div ref="moodDistributionChart" class="chart">
          <div v-if="loading" class="loading-tip">加载中...</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import Nav from '@/views/Nav.vue'
import { showToast } from 'vant'

const moodTrendChart = ref(null)
const moodDistributionChart = ref(null)
const moodMonthlyChart = ref(null)
let trendChartInstance = null
let distributionChartInstance = null
let monthlyChartInstance = null
const loading = ref(true)

// 获取本周日期标签
const getWeekDates = () => {
  const today = new Date()
  const currentDay = today.getDay()
  const monday = new Date(today)
  monday.setDate(today.getDate() - (currentDay === 0 ? 6 : currentDay - 1))
  
  const dates = []
  for (let i = 0; i < 7; i++) {
    const date = new Date(monday)
    date.setDate(monday.getDate() + i)
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    dates.push(`${month}/${day}`)
  }
  return dates
}

// 获取本月日期标签
const getMonthDates = () => {
  const today = new Date()
  const year = today.getFullYear()
  const currentMonth = today.getMonth()
  const lastDay = new Date(year, currentMonth + 1, 0).getDate()
  
  const dates = []
  for (let i = 1; i <= lastDay; i++) {
    const date = new Date(year, currentMonth, i)
    const monthStr = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    dates.push(`${monthStr}/${day}`)
  }
  return dates
}

// 初始化心情趋势图
const initTrendChart = async () => {
  try {
    const response = await request.get('/api/mood/weekly-trend')
    const weekDates = getWeekDates()
    const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

    // 创建7天的数据数组，默认值为null
    const values = new Array(7).fill(null)
    const contents = new Array(7).fill('')

    // 将返回的数据填充到对应的日期位置
    response.forEach(record => {
      const recordDate = new Date(record.date)
      const dayIndex = recordDate.getDay()
      const index = dayIndex === 0 ? 6 : dayIndex - 1
      values[index] = record.mood_value
      contents[index] = record.content
    })

    if (!trendChartInstance) {
      trendChartInstance = echarts.init(moodTrendChart.value)
    }

    const option = {
      title: {
        text: '本周心情变化折线图',
        left: 'left',
      
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const index = params[0].dataIndex
          return `${weekdays[index]} (${weekDates[index]})<br/>
                  心情值：${values[index] ?? '未记录'}<br/>
                  想法：${contents[index] || '无'}`
        }
      },
      toolbox: {
    show:true,
   
    feature: {
   
      dataView: {
        readOnly: false
      },
      magicType: {
        type: ["line", "bar"]
      },
      restore: {},
      saveAsImage: {}
    }

  },
      
      xAxis: {
        type: 'category',
        data: weekdays.map((day, index) => `${day}\n${weekDates[index]}`),
        axisLabel: { 
          interval: 0,
          fontSize: 8,
          rotate: 45, // 旋转标签，避免重叠
        }
      },
      yAxis: {
        type: 'value',
        name: '心情值',
        min: -10,
        max: 10,
        splitLine: { lineStyle: { type: 'dashed' } }
      },
      series: [{
        data: values,
        type: 'line',
       
        connectNulls: true,
       
        symbolSize: 8,
        lineStyle: { width: 3 }
      }]
    }

    trendChartInstance.setOption(option)
  } catch (error) {
    console.error('加载周趋势失败:', error)
    showToast('加载周趋势失败')
  }
}

// 初始化月度心情趋势图
const initMonthlyChart = async () => {
  try {
    const response = await request.get('/api/mood/monthly-trend')
    const monthDates = getMonthDates()

    // 创建当月天数的数据数组，默认值为null
    const values = new Array(monthDates.length).fill(null)
    const contents = new Array(monthDates.length).fill('')

    // 将返回的数据填充到对应的日期位置
    response.forEach(record => {
      const recordDate = new Date(record.date)
      const dayIndex = recordDate.getDate() - 1
      values[dayIndex] = record.mood_value
      contents[dayIndex] = record.content
    })

    if (!monthlyChartInstance && moodMonthlyChart.value) {
      monthlyChartInstance = echarts.init(moodMonthlyChart.value)
    }

    // 判断是否为移动端
    const isMobile = window.innerWidth < 768

    const option = {
      grid: {
        top: isMobile ? 30 : 40,
        left: isMobile ? 40 : 50,
        right: isMobile ? 15 : 30,
        bottom: isMobile ? 60 : 80,
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const index = params[0].dataIndex
          return `${monthDates[index]}<br/>
                  心情值：${values[index] ?? '未记录'}<br/>
                  想法：${contents[index] || '无'}`
        }
      },
      toolbox: {
        show: true,
        feature: {
          dataView: {
            readOnly: false
          },
          magicType: {
            type: ["line", "bar"]
          },
          restore: {},
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        data: monthDates,
        axisLabel: { 
          interval: 0,
          fontSize: isMobile ? 8 : 12,
          rotate: 45,
          formatter: function(value, index) {
            const day = parseInt(value.split('/')[1])
            return day % 2 === 0 ? value : ''
          }
        },
        // axisTick: {
        //   show: true,
        //   alignWithLabel: true
        // }
      },
      yAxis: {
        type: 'value',
        name: '心情值',
        min: -10,
        max: 10,
        splitLine: { lineStyle: { type: 'dashed' } },
        axisLabel: { 
          fontSize: isMobile ? 8 : 12
        }
      },
      series: [{
        data: values,
        type: 'line',
        smooth: true,
        connectNulls: true,
        
        symbolSize: isMobile ? 6 : 8,
        lineStyle: { width: isMobile ? 2 : 3 },
        markArea: {
          itemStyle: { color: 'rgba(255, 173, 177, 0.2)' },
          data: [[{ yAxis: -10 }, { yAxis: 0 }]]
        },
        markLine: {
          silent: true,
          data: [{
            yAxis: 0,
            lineStyle: { color: '#999', type: 'dashed' }
          }]
        }
      }]
    }

    monthlyChartInstance.setOption(option)
  } catch (error) {
    console.error('加载月度趋势失败:', error)
    showToast('加载月度趋势失败')
  }
}

// 初始化心情分布图
const initDistributionChart = async () => {
  try {
    const response = await request.get('/api/mood/distribution')
    
    if (!distributionChartInstance && moodDistributionChart.value) {
      distributionChartInstance = echarts.init(moodDistributionChart.value)
    }

    const option = {
      title: {
        text: '心情分布统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}次 ({d}%)'
      },
      toolbox: {

   
    feature: {
   
      dataView: {
        readOnly: false
      },
   
      restore: {},
      saveAsImage: {}
    }

  },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
        data: response.map(item => ({
          name: item.mood_type,
          value: item.count
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }
    
    distributionChartInstance.setOption(option)
  } catch (error) {
    console.error('加载心情分布失败:', error)
    showToast('加载心情分布失败')
  }
}

// 初始化所有图表
const initCharts = async () => {
  try {
    loading.value = true
    await Promise.all([
      initTrendChart(),
      initMonthlyChart(),
      initDistributionChart()
    ])
  } catch (error) {
    console.error('初始化图表失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听窗口大小变化
const handleResize = () => {
  trendChartInstance?.resize()
  monthlyChartInstance?.resize()
  distributionChartInstance?.resize()
}

onMounted(() => {
  initCharts()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChartInstance?.dispose()
  monthlyChartInstance?.dispose()
  distributionChartInstance?.dispose()
})
</script>

<style scoped lang="less">

.navbottom{
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 50px;
    margin-top: 10px;
    img{
      width: 32px;
      height: 32px;
    }
  }
.analysis-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 15px;
}

.chart-container {
  /* margin-top: 20px; */
}



.chart {
  width: 100%;
  height: 300px;
  /* background: white; */
  border-radius: 10px;
  
  /* margin-bottom: 20px; */
  /* box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); */
}

.loading-tip {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

/* PC端样式 */
@media screen and (min-width: 768px) {
  .analysis-container {
    display: flex;
    flex-direction: column;
    padding: 0;
    margin: 0;
    min-height: 100vh;
  }
  .chart-container {
 margin: 0 auto;
}

  /* 左侧导航样式 */
  :deep(.nav-container) {
    width: 200px;
    height: 100vh;
    background: #fff;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
    position: fixed;
    left: 0;
    top: 0;
    padding: 20px 0;
  }

  :deep(.nav-container .logo) {
    padding: 0 20px;
    margin-bottom: 30px;
  }

  :deep(.nav-container .nav-list) {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  :deep(.nav-container .nav-item) {
    padding: 15px 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  :deep(.nav-container .nav-item:hover) {
    background: #f5f5f5;
  }

  :deep(.nav-container .nav-item.active) {
    background: #e6f7ff;
    color: #1890ff;
    border-right: 3px solid #1890ff;
  }

  /* 主内容区样式 */
  .main-content {
    flex: 1;
    margin-left: 200px;
    padding: 40px;
    background: #f5f5f5;
  }

  .chart-container {
    max-width: 1400px;
    margin: 30px auto;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
    gap: 30px;
    padding: 0 20px;
  }

  .chart {
    height: 400px;
    margin-bottom: 0;
    transition: all 0.3s ease;
    background: #fff;
    border-radius: 12px;
    padding: 25px;
  }

  .chart:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }

  /* 图表标题样式 */
  :deep(.echarts-title) {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 20px;
  }

  /* 加载状态样式 */
  .loading-tip {
    font-size: 16px;
    color: #666;
  }
}

/* 大屏幕样式优化 */
@media screen and (min-width: 1440px) {
  :deep(.nav-container) {
    width: 240px;
  }

  .main-content {
    margin-left: 240px;
    padding: 50px;
  }

  .chart-container {
    gap: 40px;
  }

  .chart {
    height: 450px;
    padding: 30px;
  }
}

/* 超大屏幕样式优化 */
@media screen and (min-width: 1920px) {
  .chart-container {
    max-width: 1800px;
  }

  .chart {
    height: 500px;
  }
}

.chart-wrapper {
  width: 100%;
  
  .chart-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 15px;
    padding-left: 15px;
  }
}

@media screen and (max-width: 767px) {
  .chart-wrapper .chart-title {
    font-size: 14px;
    margin-bottom: 10px;
  }
}

/* 移动端月度图表样式 */
@media screen and (max-width: 767px) {
  .monthly {
    width: 100vw !important;
    margin-left: -15px;
    margin-right: -15px;
    padding: 0 10px;
  
  }

  /* 调整月度图表的容器样式 */
  .chart-wrapper {
    width: 100vw;
    margin-left: -15px;
    margin-right: -15px;


    .chart-title {
      padding: 10px 15px;
      margin: 0;
    }
  }
}
</style>






